﻿using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using System.Xml;
using System.IO;
using System.Net;
using GMusicBox.Core.Setting;

namespace GMusicBox.Core
{
    public sealed class SongStreaming
    {
        public SongStreaming(string id)
        {
            Id = id;
            LyricsUrl = "";
            SongUrl = "";
        }

        bool inRequestStack = false;

        public string Id { get; set; }

        public string LyricsUrl { get; internal set; }

        public string SongUrl { get; internal set; }

        public string AlbumThumbnailLink { get; internal set; }

        public string DownloadLyrics()
        {
            string path = Helper.GetCachePath(Helper.CacheType.Lyric, "");
            Helper.CreateDirectory(Path.GetDirectoryName(path));

            if (LyricsUrl != "")
            {
                path += Id + Path.GetExtension(LyricsUrl);
                if (!File.Exists(path))
                {
                    path += ".lrc";
                    if (!File.Exists(path))
                    {
                        path = path.Substring(0, path.Length - 4);
                        try
                        {
                            WebClient wc = new WebClient();
                            wc.DownloadFile(new Uri(LyricsUrl), path);
                            wc.Dispose();
                        }
                        catch
                        {
                            Helper.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\GMusicBox");
                            Program.CreatHiddenProfile(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\GMusicBox" + "\\temp.lrc", Encoding.UTF8.GetBytes("[00:00.01]抱歉，无法获取歌词内容或不存在此歌曲的歌词\r\n[99:99.90]"));
                            return Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\GMusicBox" + "\\temp.lrc";
                        }
                    }
                }
            }
            else
            {
                if (File.Exists(path + Id + ".lrc")) return path + Id + ".lrc";
                else if (File.Exists(path +Id + ".txt")) return path + Id + ".txt";
                else
                {
                    Helper.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\GMusicBox");
                    Program.CreatHiddenProfile(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\GMusicBox" + "\\temp.lrc", Encoding.UTF8.GetBytes("[00:00.01]抱歉，无法获取歌词内容或不存在此歌曲的歌词\r\n[99:99.90]"));
                    return Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\GMusicBox" + "\\temp.lrc";
                }
            }
            return path;
        }

        public void GetSongStreamingData()
        {
            try
            {
                string url = "http://www.google.cn/music/songstreaming?id=" + Id + MainSetting.HashData[0].Trim();
                MD5CryptoServiceProvider provider = new MD5CryptoServiceProvider();
                url = url.Replace("{hash}", BitConverter.ToString(provider.ComputeHash(Encoding.Default.GetBytes(MainSetting.HashData[1].Trim().Replace("{id}", Id)))).ToLower().Replace("-", ""));

                XmlDocument xd = new XmlDocument(); xd.Load(url);
                XmlNode xn = xd.SelectSingleNode("results/songStreaming");
                LyricsUrl = xn.SelectSingleNode("lyricsUrl").InnerText;
                SongUrl = xn.SelectSingleNode("songUrl").InnerText;
                AlbumThumbnailLink = xn.SelectSingleNode("albumThumbnailLink").InnerText;
            }
            catch (Exception ex)
            {
                if (ex.Message.IndexOf("400") != -1 && !inRequestStack)
                {
                    Helper.UpdateHash(false);
                    inRequestStack = true;
                    GetSongStreamingData();
                    inRequestStack = false;
                }
            }
        }
    }
}